package com.example.doer.reading.AppActivities;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.http.AbHttpUtil;
import com.ab.http.AbStringHttpResponseListener;
import com.example.doer.reading.AppDataModel.Topic;
import com.example.doer.reading.AppDataModel.TopicReply;
import com.example.doer.reading.R;
import com.example.doer.reading.global.MyApplication;
import com.example.doer.reading.view.PictureAndTextEditorView;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by 严旭江 on 2017/7/18.
 */

public class ReplyWritingActivity extends Activity implements View.OnClickListener {
    private TextView returnBtn;//返回按钮
    private TextView confirmBtn;//确定按钮
    private PictureAndTextEditorView replyContent;//回复内容 自定义的EditTextView
    Topic topic;//传递而来的对象
    private AbHttpUtil abHttpUtil;
    Button buttonAddPic;
    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reply_writing);
        abHttpUtil = AbHttpUtil.getInstance(ReplyWritingActivity.this);
        returnBtn = (TextView) findViewById(R.id.btnReturnTopicReplyActivity);
        confirmBtn = (TextView) findViewById(R.id.btnConfirmTopicReply);
        buttonAddPic = (Button)findViewById(R.id.WritingAddPic);
        /**
         * 自定义的EditText
         */
        replyContent = (PictureAndTextEditorView) findViewById(R.id.replyToReplyObjContent);
        returnBtn.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
        buttonAddPic.setOnClickListener(this);
        //来自TopicWithReplyActivity的请求码1001
        //获取传递的topic对象
        topic = (Topic)getIntent().getSerializableExtra("topicObjForReplyResult");
        replyContent.setHint("回复: " + topic.getTopicName());
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnReturnTopicReplyActivity://返回  则不回复
            {
                //响应码
                ReplyWritingActivity.this.setResult(2001);
                ReplyWritingActivity.this.finish();
            }
                break;
            case R.id.btnConfirmTopicReply://确定  先判断
            {
                String s = replyContent.getText().toString();
                if(!TextUtils.isEmpty(s.trim())){//不为空
                    final Intent intent = new Intent();
                    /**
                     * UserID和UserName全局获取
                     */
                    String UserID = MyApplication.user.getUserID();
                    String UserName = MyApplication.user.getUserName();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String date = sdf.format(new Date());
                    String url = "http://192.168.191.1/Reading/AnswerServlet?Action=up&userID="
                            +UserID+"&answerFromQuestID="+topic.getTopicID()+"&answerContent="+s.trim()+"&date="+date+
                            "&userName="+UserName;
                    final TopicReply topicReply = new TopicReply("",topic.getTopicID(),UserID,UserName,s,0,0,0,false,false);
                    abHttpUtil.get(url, new AbStringHttpResponseListener() {
                        @Override
                        public void onSuccess(int i, String s) {
                            intent.putExtra("returnReplyObj",topicReply);
                        }
                        @Override
                        public void onStart() {
                        }
                        @Override
                        public void onFinish() {
                        }
                        @Override
                        public void onFailure(int i, String s, Throwable throwable) {
                        }
                    });
                    ReplyWritingActivity.this.setResult(2002,intent);
                    ReplyWritingActivity.this.finish();
                }
                else {
                    Toast.makeText(ReplyWritingActivity.this,"回复内容不能为空",Toast.LENGTH_LONG).show();
                }
            }
                break;
            case R.id.WritingAddPic://点击添加Pic
            {
                /**
                 * showMore函数
                 */
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                intent.setType("image/*");
                //要求获取照片
                startActivityForResult(intent,3021);
            }
            default:
                break;
        }
    }//end onClick method
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(resultCode!=RESULT_OK) return;
        switch (requestCode){
            case 3021://从相机中获取
                ContentResolver resolver = getContentResolver();
                // 获得图片的uri
                Uri originalUri = data.getData();
                Bitmap bitmap = null;
                try {
                    //获取图片的bitmap
                    bitmap = BitmapFactory.decodeStream(resolver.openInputStream(originalUri));
                    ImageSpan imageSpan = new ImageSpan(ReplyWritingActivity.this,bitmap);
                    String tempUrl = "<img src=\"" + "http://192.168.191.1/Reading/ImageDoServlet?Action=" + "\" />";
                    SpannableString spannableString = new SpannableString(tempUrl);
                    spannableString.setSpan(imageSpan,0,tempUrl.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    int index = replyContent.getSelectionStart();
                    // 获取光标所在位置
                    Editable edit_text = replyContent.getEditableText();
                    if (index < 0 || index >= edit_text.length()) {
                        edit_text.append(spannableString);
                    } else {
                        edit_text.insert(index, spannableString);
                    }
                    edit_text.insert(index + spannableString.length(), "\n");

                }catch (FileNotFoundException e){
                    e.printStackTrace();
                }

        }//end switch
    }
//    private void appendImage(String imgUrl){
//        // 用imgUrl获取Bitmap对象
//        Bitmap bitmap = ImageLoader.getInstance().loadImageSync(
//                "file://" + imgUrl);
//        // 将Bitmap对象转换成Drawable对象
//        Resources res = getApplicationContext().getResources();
//        Drawable drawable = new BitmapDrawable(res, bitmap);
//        // 用imgUrl初始化SpannableString对象
//        SpannableString msp = new SpannableString(imgUrl);
//        // 设置图片宽高
//        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//        msp.setSpan(new ImageSpan(drawable), 0, imgUrl.length(),
//                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        // 获取Editable的对象
//        Editable edit = replyContent.getEditableText();
//        // 获取光标位置
//        int index = replyContent.getSelectionStart();
//        // 光标所在位置插入文字
//        edit.insert(index, msp);
//        Log.i("图文混排",replyContent.getText().toString());
//    }

    private void insertPic(Bitmap bitmap){
    }
    /**
     * 从相册得到的url转换为SD卡中图片路径
     */
    public String getPath(Uri uri) {
        if(TextUtils.isEmpty(uri.getAuthority())){
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        return path;
    }
}//end class
